package com.wwwarehouse.carddesk.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.wwwarehouse.carddesk.R;
import com.wwwarehouse.carddesk.activity.CardDeskActivity;
import com.wwwarehouse.carddesk.constant.CardDeskConstant;
import com.wwwarehouse.carddesk.eventbus_event.CardDeskMessageEvent;
import com.wwwarehouse.common.activity.BaseCardDeskActivity;
import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.adapter.carddesk.MyFragmentPagerAdapter;
import com.wwwarehouse.common.bean.carddesk.CardDeskMessageStableCardBean;
import com.wwwarehouse.common.bean.filter.FilterBean;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.custom_widget.CustomViewPagerInternal;
import com.wwwarehouse.common.custom_widget.ElasticScrollView;
import com.wwwarehouse.common.custom_widget.SlideBarView;
import com.wwwarehouse.common.custom_widget.state_layout.StateLayout;
import com.wwwarehouse.common.eventbus_event.DrawerMultipleCompleteEvent;
import com.wwwarehouse.common.eventbus_event.DrawerMultipleResetEvent;
import com.wwwarehouse.common.fragment.DeskDrawerMultipleFragment;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.LogUtils;
import com.wwwarehouse.common.tools.PopUpUtils;
import com.wwwarehouse.common.tripartite_widget.viewindicator.CirclePageIndicator;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import de.greenrobot.event.EventBus;

@Route(path = "/carddesk/DeskMessageFragment")
public class DeskMessageFragment extends BaseFragment {
    private View mRootView;

    private LinearLayout mResultLayout;
    private LinearLayout mEmptyLayout;
    private TextView mEmptyTxt;

    private StateLayout mStateLayout;
    private ElasticScrollView mElasticScrollView;
    private CustomViewPagerInternal mCustomViewPagerInternal;
    private CirclePageIndicator mCirclePageIndicator;
    private SlideBarView mSlideBarView;
    private List<Fragment> mFragmentList;

    private List<String> mFunctionUnitList;

    private final static int REQUEST_GET_STABLE_CARD = 10004;

    public final String ORDERSORT_DESC = "DESC";
    public final String ORDERSORT_ASC = "ASC";

    private int limitNum = 10;//默认是三十个卡片，三页的样子
    private String currentOrderSort = ORDERSORT_DESC;
    private String searchText; //搜索关键字
    private int pageNum = 1; //页数

    public final static String KEY_LIMIT = "limit";
    public final static String KEY_PAGENUM = "pagenum";
    public final static String KEY_ORDERSORT = "ordersort";
    public final static String KEY_SEARCHTEXT = "searchtext";
    public final static String KEY_TAG_LIST = "taglist";

    //抽屉数据
    private List<FilterBean> filterList;
    //请求的标签数据
    private List<CardDeskMessageStableCardBean.TaskTagsBean> listTagBean;
    //请求的标签的list string
    private LinkedList<String> tagList;

    private CardDeskMessageStableCardBean stableCardBean;
    private int currentBubblePosition = 2; //默认选中第二个
    private boolean updateOrNot;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mRootView = inflater.inflate(R.layout.fragment_desk_message, container, false);
        return mRootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initView();
        getStableCard();
        initEvent();
        EventBus.getDefault().register(this);
    }

    @Override
    public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
        return null;
    }

    private void initView() {

        mResultLayout = findView(mRootView, R.id.ll_result);
        mEmptyLayout = findView(mRootView, R.id.ll_empty);
        mEmptyTxt = findView(mRootView, R.id.tv_empty);

        mStateLayout = findView(mRootView, R.id.sl_layout);
        mStateLayout.showProgressView(false);

        mElasticScrollView = findView(mRootView, R.id.esv_elastic);
        mCustomViewPagerInternal = findView(mRootView, R.id.vpi_invite);
        mCirclePageIndicator = findView(mRootView, R.id.cpi_indicator);
        mSlideBarView = findView(mRootView, R.id.sbv_slide);

        mFragmentList = new ArrayList<>();
        mFunctionUnitList = new ArrayList<>();
        filterList = new ArrayList<>();
        listTagBean = new ArrayList<>();
        tagList = new LinkedList<>();
        stableCardBean = new CardDeskMessageStableCardBean();
    }


    private void initEvent() {


        mElasticScrollView.setOnPullListener(new ElasticScrollView.OnPullListener() {
            @Override
            public void onDownPull() {
                // 显示搜索框上的业务单位按钮
                ((BaseCardDeskActivity) mActivity).downPull_4();
            }

            @Override
            public void onUpPull() {
            }
        });


    }


    @Override
    public void filterClick() {
        if (peekFragment() == null && "message".equals(((CardDeskActivity) mActivity).getTabCurr())) {
            initDrawerLayout();
            ((BaseCardDeskActivity) mActivity).showDrawerLayout();
        }
    }

    //搜索
    @Override
    public void searchNoRealTimeClick(String text) {
        if (peekFragment() == null && "message".equals(((CardDeskActivity) mActivity).getTabCurr())) {
            searchText = text;
            getStableCard();
        }
    }

    //取消
    @Override
    public void cancelClick() {
        if (peekFragment() == null && "message".equals(((CardDeskActivity) mActivity).getTabCurr())) {
            searchText = "";
            getStableCard();
        }
    }

    //排序
    @Override
    public void sortClick(View anchor) {

        if (peekFragment() == null && "message".equals(((CardDeskActivity) mActivity).getTabCurr())) {
            PopUpUtils.showBubbleInviteSort(mActivity, anchor, currentBubblePosition, new PopUpUtils.OnChoiceListener() {
                @Override
                public void onChoice(int position) {
                    //第一个由近及远
                    if (position == 2) {
                        currentOrderSort = ORDERSORT_DESC;
                        currentBubblePosition = position;

                    } //由远及近
                    else if (position == 3) {
                        currentOrderSort = ORDERSORT_ASC;
                        currentBubblePosition = position;
                    }

                    getStableCard();//重新请求
                }
            }, null, getString(R.string.message_time_asc_sort), getString(R.string.message_time_desc_sort));
        }
    }

    public void initDrawerLayout() {
        //避免重复请求的问题
        if (filterList != null && filterList.size() != 0) {
            //初始化抽屉数据
            DeskDrawerMultipleFragment deskDrawerMultipleFragment = DeskDrawerMultipleFragment.newInstance(getString(R.string.card_message_category), filterList, 2);
            ((BaseCardDeskActivity) mActivity).setDrawerLayout(deskDrawerMultipleFragment);
        }
    }

    /**
     * 显示卡片中的数据 空页面的控制
     */
    public void showCardPage() {

        //总共多少数据 显示多少页
        int total = stableCardBean.getTotal();

        mStateLayout.showContentView();

        if (total == 0) {
            mResultLayout.setVisibility(View.GONE);
            mEmptyLayout.setVisibility(View.VISIBLE);

            if (TextUtils.isEmpty(searchText)) {
                //没有请求数据
                mEmptyTxt.setText(R.string.function_message_empty);
            } else {
                //没有搜索结果
                mEmptyTxt.setText(R.string.invite_search_no_result);
            }
        } else {
            mResultLayout.setVisibility(View.VISIBLE);
            mEmptyLayout.setVisibility(View.GONE);

            int page = (total % 10 == 0) ? total / 10 : (total / 10 + 1);

            mFragmentList.clear();
            MessageDetailsFragment messageDetailsFragment;
            for (int i = 0; i < page; i++) {
                messageDetailsFragment = new MessageDetailsFragment();
                Bundle bundle = new Bundle();

                bundle.putInt(KEY_LIMIT, limitNum);
                bundle.putInt(KEY_PAGENUM, i + 1);
                bundle.putString(KEY_ORDERSORT, currentOrderSort);
                bundle.putString(KEY_SEARCHTEXT, searchText);
                bundle.putSerializable(KEY_TAG_LIST, tagList);

                messageDetailsFragment.setArguments(bundle);
                mFragmentList.add(messageDetailsFragment);
            }

            mCustomViewPagerInternal.setAdapter(new MyFragmentPagerAdapter(getChildFragmentManager(), mFragmentList));


            /** 底部slidebar显示问题  */
            if (page <= 6) {
                if (page == 1) {
                    mCirclePageIndicator.setVisibility(View.GONE);
                    mSlideBarView.setVisibility(View.GONE);
                } else {
                    mCirclePageIndicator.setVisibility(View.VISIBLE);
                    mSlideBarView.setVisibility(View.GONE);

                    mCirclePageIndicator.setViewPager(mCustomViewPagerInternal, 0);
                }
            } else {
                mCirclePageIndicator.setVisibility(View.GONE);
                mSlideBarView.setVisibility(View.VISIBLE);

                mSlideBarView.setTotalPage(page);
                mSlideBarView.setOnSlideChange(new SlideBarView.OnSlideChange() {
                    @Override
                    public void onSlideChange(int page) {
                        mCustomViewPagerInternal.setCurrentItem(page, false);
                    }
                });

                mSlideBarView.setViewPagerInternal(mCustomViewPagerInternal);
            }
        }
    }

    /**
     * 获取固定卡片的值
     */
    private void getStableCard() {
        Map dataMap = new HashMap();
        dataMap.put("actionType", "I");
        dataMap.put("searchText", searchText);
        if (tagList == null || tagList.size() == 0) {
            //这个时候给null给后台
            dataMap.put("taskTags", null);
        } else {
            dataMap.put("taskTags", tagList);
        }
        dataMap.put("buId", null);
        dataMap.put("limit", "10");
        dataMap.put("page", "1");
        //通过时间的由远及近或者由近及远
        dataMap.put("orderSort", currentOrderSort);
        dataMap.put("orderType", "CREATE_TIME");

        LogUtils.showErrLog("接口： " + CardDeskConstant.URL_GET_FUNCTION_INFO + " 发送请求" + dataMap.toString());
        NoHttpUtils.httpPost(CardDeskConstant.URL_GET_FUNCTION_INFO, dataMap, mOnResponseListener, REQUEST_GET_STABLE_CARD);

    }

    NoHttpUtils.OnResponseListener mOnResponseListener = new NoHttpUtils.OnResponseListener() {
        @Override
        public void onSucceed(CommonClass commonClass, int what) {
            switch (what) {
                //接口顺序：  标签单独请求 ， 请求固定卡片之后再请求信息卡片 ， 固定卡片与信息卡片任意一个失败，都从固定卡片开始请求。
                case REQUEST_GET_STABLE_CARD:
                    if ("0".equals(commonClass.getCode())) {
                        LogUtils.showErrLog("" + commonClass.getData().toString());
                        stableCardBean = JSON.parseObject(commonClass.getData().toString(), CardDeskMessageStableCardBean.class);

                        showCardPage();

                        if (listTagBean == null || listTagBean.size() == 0 || updateOrNot) {
                            updateOrNot = false;
                            listTagBean = stableCardBean.getTaskTags();
                            filterList = new LinkedList<>();
                            FilterBean filterBean;
                            for (CardDeskMessageStableCardBean.TaskTagsBean bean : listTagBean) {
                                //默认全部选中
                                filterBean = new FilterBean(false, bean.getTagRemark());
                                filterList.add(filterBean);
                            }
                        }

                        initDrawerLayout();

                    } else {
                        //其他的同步线程没有处理的code
                        mStateLayout.showSystemView(commonClass.getMsg(), false);
                        mStateLayout.setSystemListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mStateLayout.showProgressView(false);
                                getStableCard();
                            }
                        });
                    }
                    break;
                default:
                    break;
            }
        }

        @Override
        public void onFailed(String result, int what) {
            switch (what) {
                //接口顺序：  好吧，只要一个接口了
                case REQUEST_GET_STABLE_CARD:
                    mStateLayout.showNetworkView(false);
                    mStateLayout.setNetworkListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mStateLayout.showProgressView(false);
                            getStableCard();
                        }
                    });
                    break;
            }

        }

        @Override
        public void onFinish(int what) {
            mStateLayout.showContentView();
        }
    };

    @Override
    public void setTitle() {

    }

    @Override
    public void requestDatas() {

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    //页面切换的事件
    public void onEventMainThread(CardDeskMessageEvent event) {
        if("message".equals(event.getMsg())){
            //大切换应该开始初始 drawerlayout
            updateOrNot = true;
            //同时将保存的请求tag清空
            tagList = new LinkedList<>();
            getStableCard();

            initEvent();
        }else if("clear_back_stack".equals(event.getMsg())){
            ((BaseCardDeskActivity)mActivity).cleanBackStack();
            getStableCard();
        }
    }

    //抽屉的切换事件
    public void onEventMainThread(Object event) {

        if (event instanceof DrawerMultipleCompleteEvent && ("message".equals(((CardDeskActivity) mActivity).getTabCurr())) && peekFragment() == null) {
            tagList = new LinkedList<>();
            DrawerMultipleCompleteEvent completeEvent = (DrawerMultipleCompleteEvent) event;
            if (completeEvent != null) {
                Set<Integer> set = completeEvent.getSelectedPositionSet();
                for (Integer intNum : set) {
                    if (intNum < listTagBean.size()) {
                        tagList.add(listTagBean.get(intNum).getTagValue());
                    }
                }

                //发起请求
                getStableCard();
            }

        }

        if (event instanceof DrawerMultipleResetEvent && ("message".equals(((CardDeskActivity) mActivity).getTabCurr())) && peekFragment() == null) {
            tagList = new LinkedList<>();
            ((BaseCardDeskActivity) mActivity).hideDrawerLayout();
            //发起请求
            getStableCard();
        }
    }
}